if (Drupal.jsEnabled) {
	$(document).ready(function () {
		$('body').click(function(e) {
			if($(e.target)[0].tagName != 'INPUT') {
				$('#ac-form-xpath').attr('value', getElementXPath(e.target));
				$('#ac-form-xpath-preview').html(getElementXPath(e.target));
				$('.ac_template_selected').each(function() {
					$(this).removeClass('ac_template_selected');
				});
				$(e.target).addClass('ac_template_selected');
			}
		});
		$(document).keypress(function(event) {
			if(!$('.ac_template_selected')) {
				return false;
			}
			if(event.keyCode == 119) {
				//Key up - move up the DOM
				var current = $('.ac_template_selected');
				var parent = current.parent();
				current.removeClass('ac_template_selected');
				parent.addClass('ac_template_selected');
				$('#ac-form-xpath').attr('value', getElementXPath(parent[0]));
				$('#ac-form-xpath-preview').html(getElementXPath(parent[0]));
				return false;
			}
			if(event.keyCode == 115 && $('.ac_template_selected:first-child')) {
				//Key down - move down the DOM
				var current = $('.ac_template_selected');
				var child = $('.ac_template_selected:first-child');
				current.removeClass('ac_template_selected');
				child.addClass('ac_template_selected');
				$('#ac-form-xpath').attr('value', getElementXPath(child[0]));
				$('#ac-form-xpath-preview').html(getElementXPath(child[0]));
				return false;
			}
			if(event.keyCode == 100 && $('.ac_template_selected').next()) {
				//Key right - move to next DOM ELEMENT
				var current = $('.ac_template_selected');
				var next = current.next();
				current.removeClass('ac_template_selected');
				next.addClass('ac_template_selected');
				$('#ac-form-xpath').attr('value', getElementXPath(next[0]));
				$('#ac-form-xpath-preview').html(getElementXPath(next[0]));
				return false;
			}
			if(event.keyCode == 97 && $('.ac_template_selected').prev()) {
				//Key left - move to previous DOM ELEMENT
				var current = $('.ac_template_selected');
				var prev = current.prev();
				current.removeClass('ac_template_selected');
				prev.addClass('ac_template_selected');
				$('#ac-form-xpath').attr('value', getElementXPath(prev[0]));
				$('#ac-form-xpath-preview').html(getElementXPath(prev[0]));
				return false;
			}
			
		});
	});
}

getElementXPath = function(elm) {
       for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) {
         if (elm.hasAttribute('id')) {
           segs.unshift('id(\'' + elm.getAttribute('id') + '\')')
           return segs.join('/')
         }
         else if (elm.hasAttribute('class'))
           segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]')
         else {
           for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling)
             if (sib.localName == elm.localName) i++
           segs.unshift(elm.localName.toLowerCase() + '[' + i + ']')
         }
       }
       return segs.length ? '/' + segs.join('/') : null
     }